package concursos.ejb;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.ScheduleExpression;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.TimerService;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import concursos.daos.LembreteDAO;
import concursos.modelos.Lembrete;

@Stateless
public class EnviaEmailEjb {

	@Resource
	private TimerService timerService;
	private List<Lembrete> lembretes = new ArrayList<Lembrete>();
	private LembreteDAO lembreteDAO;
	@PersistenceContext(unitName = "meusconcursosejb")
	private EntityManager manager;

	public LembreteDAO getLembreteDAO() {
		if (this.lembreteDAO == null)
			this.lembreteDAO = new LembreteDAO(this.manager);
		return this.lembreteDAO;
	}

	@SuppressWarnings("deprecation")
	@Schedule(dayOfWeek = "*", hour = "14", minute = "25")
	public void agendar() throws NamingException, MessagingException {
		Date data = new Date();
		SimpleDateFormat formatador = new SimpleDateFormat("dd/MM/yyyy");

		this.lembretes = this.getLembreteDAO().lembretesEnviarEmail(
				formatador.format(data));

		if (this.lembretes.size() > 0) {
			System.out.println("Agendando emails...");

			this.timerService.createCalendarTimer(new ScheduleExpression()
					.month((data.getMonth() + 1)).dayOfMonth(data.getDate())
					.hour(14).minute(26));
		} else {
			System.out.println("Nenhum email pra enviar hoje");
		}

	}

	@Timeout
	public void enviarEmail() throws Exception {
		System.out.println("Enviando email...");
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");

		Session session = Session.getInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(
								"meusconcursospdsc@gmail.com", "meusconcursos");
					}
				});
		try {

			for (Lembrete lembrete : this.lembretes) {
				Message message = new MimeMessage(session);
				message.setFrom(new InternetAddress(
						"meusconcursospdsc@gmail.com"));

				message.setRecipients(
						Message.RecipientType.TO,
						InternetAddress.parse(lembrete.getConcurso()
								.getUsuario().getEmail()));
				message.setSubject("Meus Concursos - Lembrete: "
						+ lembrete.getTitulo());
				message.setText(lembrete.getInformacao());

				Transport.send(message);
				System.out.println("Email enviado para: "
						+ lembrete.getConcurso().getUsuario().getEmail());

				lembrete.setEnviarEmail(false);
				this.getLembreteDAO().salvarLembrete(lembrete);
			}

		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}
